import {Component, OnInit} from '@angular/core';
import {App, NavController, Platform, ViewController} from 'ionic-angular';
import {CollectPage} from "../collect/collect";
import {ManagementPage} from "../management/management";
import {services} from "../../../providers/service";
import {Http} from "@angular/http";
import {NewCreatPage} from "../newcreat/newcreat";
import {BarcodeScanner} from "@ionic-native/barcode-scanner";
import {CjDelStatusPage} from "../cjDelStatus/cjDelStatus";
import {interfaceUrls} from "../../../providers/serverUrls";
import {ResultPage} from "../result/result";
import {OuterService} from "../provider/storage-service";
//处理库存不存在的问题
import {AppPopup} from "../../../util/popup";
import {UserService} from "../../../providers/user-service";
import {UserLogin} from "../../../modules/app-user/user-login/user-login";
import {StorageService} from "../../../providers/storage-service";


@Component({
    selector: 'storage',
    templateUrl: 'storage.html',
})
export class StoragePage implements OnInit {
    imgURL: string = interfaceUrls.imgUrl;

    activeModelText = "当前扫码进度将会保留<br/>";
    hasStorage = true;                    //设置库存是否为空
    isShowEditModel = false;              //更多操作的弹框
    showAlert = true;                     //控制弹框的显隐
    myItems = [];
    index;                                //遍历的索引值
    keyword;                              //关键字
    showMc = false;
    pageNo = 1;
    pageSize = 10;          //每页数量
    count = 0;              //总数
    scanData;               //单个出库单信息
    isOnFocus: boolean = false; //控制按钮新建出库单按钮显示隐藏

//处理库存不存在的问题，库存不存在图片报错
    product = {
        productId: "", productImg: "", productName: ""
    };
    productList = {
        productId: "", productImg: "", productName: ""
    };
    //
    constructor(public navCtrl: NavController,
                public service: services,
                public http: Http,
                private userServ: UserService,
                private app: App,
                private popup: AppPopup,
                private outerServ: OuterService,
                public barcodeScanner: BarcodeScanner,
                public platform: Platform,
                public viewCtrl: ViewController,
                private storageServ: StorageService,) {

        viewCtrl.didEnter.subscribe(() => this.onDidEnter());

    }

    // didEnter回调
    public onDidEnter() {
        this.service.activeModelText = this.activeModelText;
        this.search();
    }

    ionViewWillEnter() {
        this.userServ.getPersonInfo()
            .then(() => {
            })
            .catch(err => {
                console.error("用户详情获取失败：", err);
                if (err.errorMassage == "未登录或登录超时！") {
                    this.popup.alert(err.errorMassage)
                        .then(() => {
                            this.app.getRootNav().setRoot(UserLogin);
                        });
                }
            });
    }

    ngOnInit() {
    }

    blurInput() {
        this.isOnFocus = false;
    }

    focusInput() {
        this.isOnFocus = true;
    }


    ToNewcreat() {
        this.storageServ.productLists()
            .then(res => {
                console.info("获取产品列表成功：", res);
                if (res.infoData instanceof Array && res.infoData.length) {
                    this.productList = res.infoData;
                    this.product = res.infoData[0];
                    this.navCtrl.push(NewCreatPage);
                } else {
                    this.popup.alert("你没有可出库的产品");
                }
            })
            .catch(err => {
                console.error("获取产品列表失败：", err);
                this.popup.alert(err.errorMassage);
            });
    }

    ToCollectPage() {
        this.navCtrl.setRoot(CollectPage);
    }

    // 完成按钮 -- 跳转到确认出库页面
    ToManagement(idx) {
        this.outerServ.outerId = this.myItems[idx].id;
        console.info("点击完成的时候的数据", this.service.collectedCount);
        this.navCtrl.push(ManagementPage, {
            thisProductInfo: this.myItems[idx]
        });
    }

    //更多操作
    showEditModel(idx) {
        this.index = idx;
        this.isShowEditModel = true;
        this.showMc = true;
    }

    //点击空白处
    closeMC() {
        this.showMc = false;
        this.isShowEditModel = false;
    }

    toShowAlert() {
        this.showAlert = false;
        this.isShowEditModel = false;
    }

    btnCancel() {
        this.showAlert = true;
        this.isShowEditModel = false;
        this.showMc = false;
    }

    //更多操作 -- 撤销出库单 -- 确定
    btnChoose() {
        console.log("出库单id: ", this.myItems[this.index].id);
        this.showAlert = true;
        this.isShowEditModel = false;
        this.showMc = false;
        let param = {
            "id": this.myItems[this.index].id
        }
        this.storageServ.revoke(param)
            .then(res => {
                console.info("出库单_撤销成功：", res);
                this.search();
            })
            .catch(err => {
                console.error("出库单_撤销失败：", err);
                this.popup.alert(err.errorMassage);
            });
    }

    // -- 更多操作 -- 删除一箱 -- 删除扫码
    deleteBox() {
        console.log(this.index)
        this.barcodeScanner.scan().then((barcodeData) => {
            if (barcodeData.text == null || barcodeData.text == '') {
                this.service.isReturn = true;
                return;
            }
            this.service.boxNo = barcodeData.text;
            let param = {
                "boxNo": barcodeData.text,                   //箱码
                "outId": this.myItems[this.index].id,        //出库单ID
                "outNo": this.myItems[this.index].outNo      //出库单号
            }
            this.storageServ.delscandetails(param)
                .then(res => {
                    console.info("出库单_删除一箱扫码成功：", res);
                    this.navCtrl.push(CjDelStatusPage, {data: res});
                })
                .catch(err => {
                    console.error("出库单_删除一箱扫码失败：", err);
                    this.navCtrl.push(CjDelStatusPage, {data: err});
                });
        }, (err) => {
            console.error(err);
        });
        this.isShowEditModel = false;
        this.showMc = false;
    }

    //继续 -- 出库扫码
    toScan(index) {
        this.outerServ.outerId = this.myItems[index].id;
        this.barcodeScanner.scan().then((barcodeData) => {
            console.log(barcodeData.text);
            if (barcodeData.text == null || barcodeData.text == '') {
                this.service.isReturn = true;
                console.info("取消扫码后的时间：", this.service.isReturn);
                return;
            }
            this.service.boxNo = barcodeData.text;
            let param = {
                "boxNo": barcodeData.text,                      //箱码
                "outId": this.myItems[index].id,                //出库单ID
                "outNo": this.myItems[index].outNo,             //出库单号
                "productId": this.myItems[index].productId,     //产品ID
            }
            this.storageServ.scan(param)
                .then(res => {
                    console.info("出库单_出库扫码成功：", res);
                    this.navCtrl.push(ResultPage, {data: res, thisProductInfo: this.myItems[index]});
                })
                .catch(err => {
                    console.error("出库单_出库扫码失败：", err);
                    this.navCtrl.push(ResultPage, {data: err, thisProductInfo: this.myItems[index]});
                });
        }, (err) => {
            console.error(err);
        });

    }

    //下拉刷新
    doRefresh(refresher) {
        this.pageNo = 1;
        let param = {
            "keyword": this.keyword
        }
        this.storageServ.outList(param, this.pageNo, this.pageSize)
            .then(res => {
                console.info("下拉刷新成功：", res);
                this.count = Math.ceil(res.infoData.count / this.pageSize);
                this.myItems = res.infoData.items;
                refresher.complete();
            })
            .catch(err => {
                console.error("下拉刷新失败：", err);
                refresher.complete();
                this.popup.alert(err.errorMassage);
            });
    }

    //上拉加载更多
    doInfinite(infiniteScroll) {
        if (this.count > this.pageNo) {
            this.pageNo += 1;
            let param = {
                "keyword": this.keyword
            }
            this.storageServ.outList(param, this.pageNo, this.pageSize)
                .then(res => {
                    console.info("上拉加载更多成功：", res);
                    this.count = Math.ceil(res.infoData.count / this.pageSize);
                    this.myItems = this.myItems.concat(res.infoData.items);
                    infiniteScroll.complete();
                })
                .catch(err => {
                    console.error("上拉加载失败：", err);
                    infiniteScroll.complete();
                    this.popup.alert(err.errorMassage);
                });
        } else {
            infiniteScroll.complete();
        }

    }

    //搜索
    search() {
        this.pageNo = 1;
        let param = {
            "keyword": this.keyword
        }
        this.storageServ.outList(param, this.pageNo, this.pageSize)
            .then(res => {
                console.info("出库单_列表查询成功：", res);
                this.myItems = res.infoData.items;
                this.count = Math.ceil(res.infoData.count / this.pageSize);
                if (res.infoData.count == 0) {
                    this.hasStorage = false;
                } else {
                    this.hasStorage = true;
                }
            })
            .catch(err => {
                console.error("出库单_列表查询失败：", err);
                this.popup.alert(err.errorMassage);
            });
    }

    //清空搜索
    clearInput() {
        this.keyword = "";
        this.search();
    }


}
